package com.itheima.algorithm.hashtable;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class E08Leetcode819 {
    public String mostCommonWord1(String paragraph,String[] banned){
        String[] split=paragraph.toLowerCase().split("[^A-Za-z]+");

       HashSet<String> set=new HashSet<>();
        for(String b:banned){
            set.add(b);
        }
        HashMap<String,Integer> map=new HashMap<>();
        for(String key:split){
            if(!set.contains(key)){
                map.compute(key,(k,v)->v==null?1:v+1);
            }
        }
        Set<Map.Entry<String, Integer>> entries = map.entrySet();
        int maxLength=0;
        for(Map.Entry<String, Integer> entry:entries){
            maxLength=Math.max(entry.getValue(),maxLength);
        }

        Set<Map.Entry<String, Integer>> entries2 = map.entrySet();
        for(Map.Entry<String, Integer> entry:entries2){
            String ans=entry.getKey();
            int ansNum=entry.getValue();
            if(ansNum==maxLength){
                return ans;
            }
        }

        return "";
    }

    public String mostCommonWord(String paragraph,String[] banned){
        Set<String> set=Set.of(banned);
        HashMap<String,Integer> map=new HashMap<>();
        char[] chars=paragraph.toLowerCase().toCharArray();
        StringBuilder sb=new StringBuilder();
        for(char ch:chars){
            if(ch>='a' && ch<='z'){
                sb.append(ch);
            }else{
                String key=sb.toString();
                if(!set.contains(key)){
                    map.compute(key,(k,v)->v==null?1:v+1);
                }
                sb=new StringBuilder();
            }
        }
            if(sb.length()>0){
                String key=sb.toString();
                if(!set.contains(key)){
                    map.compute(key,(k,v)->v==null?1:v+1);
                }
            }

        int max=0;
        String maxKey=null;
        for(Map.Entry<String,Integer> e:map.entrySet()){
            Integer value=e.getValue();
            if(value>max){
                max=value;
                maxKey=e.getKey();
            }
        }
        return maxKey;
    }
    public static void main(String[] args) {
        E08Leetcode819 e08=new E08Leetcode819();
        System.out.println(e08.mostCommonWord("Bob hit a ball, the hit BALL " +
                        "flew far after it was hit.",
                new String[]{"hit"}));
    }
}
